/*
 * CameraFrame.java
 *
 * Created on __DATE__, __TIME__
 */

package com.javapda.app.camera.gui;

import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.UnsupportedCommOperationException;

import java.awt.Component;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import javax.swing.ImageIcon;

import com.javapda.c328r.C328rCameraConfiguration;
import com.javapda.c328r.C328rCameraImpl;
import com.javapda.c328r.util.PortAvailabilityUtil;
import com.javapda.util.FileUtil;
import com.javapda.util.GuiUtility;
import com.javapda.util.MiscUtil;

/**
 *
 * @author  __USER__
 */
public class CameraFrame extends javax.swing.JFrame {
	private static final long serialVersionUID = 1L;
	private static final String DEFAULT_TITLE = "Camera App";
	private CommPortIdentifier commPort;
	private SerialPort serialPort;
	private C328rCameraImpl cam;
	private PreviewRunnable previewRunnable;
	private byte[] snapshotPic;
	private byte[] previewPic;

	/** Creates new form CameraFrame */
	public CameraFrame(String commPortName) {
		this();
		if ( commPortName != null ) {
			setCommPortByName(commPortName);
			if (cam == null) {
				syncCamera();
				previewPhotoButton.setEnabled(true);
				playPreview();
			}
		}
	}

	public CameraFrame() {
		initComponents();
		previewPhotoButton.setEnabled(false);
		addWindowListener(new WindowAdapter() {

			public void windowClosing(WindowEvent e) {
				System.out.println("WINDOW CLOSING");
				exit();
			}

		});

		snapshotPhotoButton.setIcon(getScaledPhoto(
				"/images/C328R_20080111_172216.jpg", Math.max(
						snapshotPhotoButton.getWidth(), snapshotPhotoButton
								.getHeight())));
		previewPhotoButton.setIcon(getScaledPhoto(
		//				"/images/processing.gif", Math.max(
				"/images/C328R_20080109_180114.jpg", Math.max(
						previewPhotoButton.getWidth(), previewPhotoButton
								.getHeight())));
		pack();
	}

	void setSnaphotPhoto(byte[] data) {
		ImageIcon ic = getScaledPhoto(data, Math.max(snapshotPhotoButton
				.getWidth(), snapshotPhotoButton.getHeight()));
		snapshotPhotoButton.setIcon(ic);
	}

	void setPreviewPhoto(final byte[] data) {
		java.awt.EventQueue.invokeLater(new Runnable() {
			public void run() {
				ImageIcon ic = getScaledPhoto(data, Math.max(previewPhotoButton
						.getWidth(), snapshotPhotoButton.getHeight()));
				previewPhotoButton.setIcon(ic);
			}
		});

		//		ImageIcon ic = getScaledPhoto(data, Math.max(
		//						previewPhotoButton.getWidth(), snapshotPhotoButton
		//								.getHeight()));
		//		previewPhotoButton.setIcon(ic);
	}

	private ImageIcon getScaledPhoto(String cpImagePath, int max) {
		byte[] imgb = GuiUtility.getBytesFromClasspath(cpImagePath);
		return getScaledPhoto(imgb, max);
	}

	private ImageIcon getScaledPhoto(byte[] imgb, int max) {
		BufferedImage bi = GuiUtility.getImageFromByteArray(imgb);
		Image img = GuiUtility.getThumbnail(bi, Math.max(snapshotPhotoButton
				.getWidth(), snapshotPhotoButton.getHeight()));
		ImageIcon ic = new ImageIcon(img);
		return ic;
	}

	/** This method is called from within the constructor to
	 * initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is
	 * always regenerated by the Form Editor.
	 */
	//GEN-BEGIN:initComponents
	// <editor-fold defaultstate="collapsed" desc=" Generated Code ">
	private void initComponents() {
		snapshotResolutionGroup = new javax.swing.ButtonGroup();
		jPanel1 = new javax.swing.JPanel();
		syncButton = new javax.swing.JButton();
		resetButton = new javax.swing.JButton();
		portSelectButton = new javax.swing.JButton();
		previewButton = new javax.swing.JButton();
		leftSidePanel = new javax.swing.JPanel();
		previewPicturePane = new javax.swing.JPanel();
		previewPhotoButton = new javax.swing.JButton();
		previewSettingsPanel1 = new com.javapda.app.camera.gui.PreviewSettingsPanel();
		playButton = new javax.swing.JButton();
		stopButton = new javax.swing.JButton();
		rightSidePanel = new javax.swing.JPanel();
		snapshotPicturePane = new javax.swing.JPanel();
		snapshotPhotoButton = new javax.swing.JButton();
		snapshotSettingsPanel1 = new com.javapda.app.camera.gui.SnapshotSettingsPanel();
		goButton = new javax.swing.JButton();
		cameraStatusBar1 = new com.javapda.app.camera.gui.CameraStatusBar();
		mainMenuBar = new javax.swing.JMenuBar();
		fileMenu = new javax.swing.JMenu();
		exitMenuItem = new javax.swing.JMenuItem();
		editMenu = new javax.swing.JMenu();

		setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
		setTitle("Camera App");
		jPanel1.setBackground(new java.awt.Color(204, 204, 204));
		syncButton.setText("Sync");
		syncButton.setEnabled(false);
		syncButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				syncButtonActionPerformed(evt);
			}
		});

		resetButton.setText("Reset");
		resetButton.setEnabled(false);
		resetButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				resetButtonActionPerformed(evt);
			}
		});

		portSelectButton.setText("Select Port");
		portSelectButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				portSelectButtonActionPerformed(evt);
			}
		});

		previewButton.setText("Preview");
		previewButton.setToolTipText("Click to get preview");
		previewButton.setEnabled(false);
		previewButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				previewButtonActionPerformed(evt);
			}
		});

		org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(
				jPanel1);
		jPanel1.setLayout(jPanel1Layout);
		jPanel1Layout.setHorizontalGroup(jPanel1Layout.createParallelGroup(
				org.jdesktop.layout.GroupLayout.LEADING).add(
				jPanel1Layout.createSequentialGroup().add(portSelectButton)
						.addPreferredGap(
								org.jdesktop.layout.LayoutStyle.RELATED).add(
								syncButton).addPreferredGap(
								org.jdesktop.layout.LayoutStyle.RELATED).add(
								previewButton).addPreferredGap(
								org.jdesktop.layout.LayoutStyle.RELATED).add(
								resetButton).addContainerGap(458,
								Short.MAX_VALUE)));
		jPanel1Layout.setVerticalGroup(jPanel1Layout.createParallelGroup(
				org.jdesktop.layout.GroupLayout.LEADING).add(
				jPanel1Layout.createSequentialGroup().add(
						jPanel1Layout.createParallelGroup(
								org.jdesktop.layout.GroupLayout.BASELINE).add(
								syncButton).add(resetButton).add(
								portSelectButton).add(previewButton))
						.addContainerGap(63, Short.MAX_VALUE)));

		leftSidePanel.setBorder(javax.swing.BorderFactory.createTitledBorder(
				null, "Preview",
				javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION,
				javax.swing.border.TitledBorder.DEFAULT_POSITION,
				new java.awt.Font("Tahoma", 1, 12)));
		previewPicturePane.setBackground(new java.awt.Color(102, 102, 102));
		previewPicturePane.setBorder(javax.swing.BorderFactory
				.createEtchedBorder());
		previewPhotoButton.setBackground(new java.awt.Color(153, 153, 153));
		previewPhotoButton
				.addActionListener(new java.awt.event.ActionListener() {
					public void actionPerformed(java.awt.event.ActionEvent evt) {
						previewPhotoButtonActionPerformed(evt);
					}
				});

		org.jdesktop.layout.GroupLayout previewPicturePaneLayout = new org.jdesktop.layout.GroupLayout(
				previewPicturePane);
		previewPicturePane.setLayout(previewPicturePaneLayout);
		previewPicturePaneLayout.setHorizontalGroup(previewPicturePaneLayout
				.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
				.add(previewPhotoButton,
						org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 305,
						Short.MAX_VALUE));
		previewPicturePaneLayout.setVerticalGroup(previewPicturePaneLayout
				.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
				.add(previewPhotoButton,
						org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 243,
						Short.MAX_VALUE));

		playButton.setText("Play");
		playButton.setEnabled(false);
		playButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				playButtonActionPerformed(evt);
			}
		});

		stopButton.setText("Stop");
		stopButton.setEnabled(false);
		stopButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				stopButtonActionPerformed(evt);
			}
		});

		org.jdesktop.layout.GroupLayout leftSidePanelLayout = new org.jdesktop.layout.GroupLayout(
				leftSidePanel);
		leftSidePanel.setLayout(leftSidePanelLayout);
		leftSidePanelLayout
				.setHorizontalGroup(leftSidePanelLayout
						.createParallelGroup(
								org.jdesktop.layout.GroupLayout.LEADING)
						.add(
								leftSidePanelLayout
										.createSequentialGroup()
										.addContainerGap()
										.add(
												leftSidePanelLayout
														.createParallelGroup(
																org.jdesktop.layout.GroupLayout.LEADING)
														.add(
																previewPicturePane,
																org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
																org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
																org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
														.add(
																leftSidePanelLayout
																		.createSequentialGroup()
																		.add(
																				previewSettingsPanel1,
																				org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
																				org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
																				org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
																		.add(
																				15,
																				15,
																				15)
																		.add(
																				leftSidePanelLayout
																						.createParallelGroup(
																								org.jdesktop.layout.GroupLayout.LEADING)
																						.add(
																								stopButton)
																						.add(
																								playButton))))
										.addContainerGap(30, Short.MAX_VALUE)));
		leftSidePanelLayout
				.setVerticalGroup(leftSidePanelLayout
						.createParallelGroup(
								org.jdesktop.layout.GroupLayout.LEADING)
						.add(
								org.jdesktop.layout.GroupLayout.TRAILING,
								leftSidePanelLayout
										.createSequentialGroup()
										.add(
												previewPicturePane,
												org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
												org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
												org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
										.addPreferredGap(
												org.jdesktop.layout.LayoutStyle.RELATED,
												58, Short.MAX_VALUE)
										.add(
												leftSidePanelLayout
														.createParallelGroup(
																org.jdesktop.layout.GroupLayout.LEADING)
														.add(
																leftSidePanelLayout
																		.createSequentialGroup()
																		.addPreferredGap(
																				org.jdesktop.layout.LayoutStyle.RELATED)
																		.add(
																				previewSettingsPanel1,
																				org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
																				org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
																				org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
														.add(
																leftSidePanelLayout
																		.createSequentialGroup()
																		.add(
																				15,
																				15,
																				15)
																		.add(
																				playButton)
																		.addPreferredGap(
																				org.jdesktop.layout.LayoutStyle.RELATED)
																		.add(
																				stopButton)))
										.addContainerGap()));

		rightSidePanel.setBorder(javax.swing.BorderFactory.createTitledBorder(
				null, "Snapshot",
				javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION,
				javax.swing.border.TitledBorder.DEFAULT_POSITION,
				new java.awt.Font("Tahoma", 1, 12)));
		snapshotPicturePane.setBorder(javax.swing.BorderFactory
				.createEtchedBorder());
		snapshotPhotoButton.setBackground(new java.awt.Color(102, 102, 102));
		snapshotPhotoButton.setBorder(javax.swing.BorderFactory
				.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
		snapshotPhotoButton
				.addActionListener(new java.awt.event.ActionListener() {
					public void actionPerformed(java.awt.event.ActionEvent evt) {
						snapshotPhotoButtonActionPerformed(evt);
					}
				});

		org.jdesktop.layout.GroupLayout snapshotPicturePaneLayout = new org.jdesktop.layout.GroupLayout(
				snapshotPicturePane);
		snapshotPicturePane.setLayout(snapshotPicturePaneLayout);
		snapshotPicturePaneLayout.setHorizontalGroup(snapshotPicturePaneLayout
				.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
				.add(snapshotPhotoButton,
						org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 313,
						Short.MAX_VALUE));
		snapshotPicturePaneLayout.setVerticalGroup(snapshotPicturePaneLayout
				.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
				.add(snapshotPhotoButton,
						org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 243,
						Short.MAX_VALUE));

		goButton.setText("Go!");
		goButton.setToolTipText("Click to take snapshot");
		goButton.setEnabled(false);
		goButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				goButtonActionPerformed(evt);
			}
		});

		org.jdesktop.layout.GroupLayout rightSidePanelLayout = new org.jdesktop.layout.GroupLayout(
				rightSidePanel);
		rightSidePanel.setLayout(rightSidePanelLayout);
		rightSidePanelLayout
				.setHorizontalGroup(rightSidePanelLayout
						.createParallelGroup(
								org.jdesktop.layout.GroupLayout.LEADING)
						.add(
								rightSidePanelLayout
										.createSequentialGroup()
										.addContainerGap()
										.add(
												rightSidePanelLayout
														.createParallelGroup(
																org.jdesktop.layout.GroupLayout.LEADING)
														.add(
																snapshotPicturePane,
																org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
																org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
																org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
														.add(
																rightSidePanelLayout
																		.createSequentialGroup()
																		.add(
																				snapshotSettingsPanel1,
																				org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
																				org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
																				org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
																		.addPreferredGap(
																				org.jdesktop.layout.LayoutStyle.RELATED)
																		.add(
																				goButton,
																				org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
																				68,
																				org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
										.add(22, 22, 22)));
		rightSidePanelLayout
				.setVerticalGroup(rightSidePanelLayout
						.createParallelGroup(
								org.jdesktop.layout.GroupLayout.LEADING)
						.add(
								org.jdesktop.layout.GroupLayout.TRAILING,
								rightSidePanelLayout
										.createSequentialGroup()
										.add(
												snapshotPicturePane,
												org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
												org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
												org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
										.addPreferredGap(
												org.jdesktop.layout.LayoutStyle.RELATED,
												48, Short.MAX_VALUE)
										.add(
												rightSidePanelLayout
														.createParallelGroup(
																org.jdesktop.layout.GroupLayout.LEADING)
														.add(
																rightSidePanelLayout
																		.createSequentialGroup()
																		.add(
																				0,
																				0,
																				0)
																		.add(
																				snapshotSettingsPanel1,
																				org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
																				org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
																				org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
														.add(
																rightSidePanelLayout
																		.createSequentialGroup()
																		.add(
																				22,
																				22,
																				22)
																		.add(
																				goButton,
																				org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
																				73,
																				org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
										.addContainerGap()));

		cameraStatusBar1.setBorder(javax.swing.BorderFactory
				.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

		mainMenuBar.setToolTipText("You are on the Main Menu Bar");
		fileMenu.setMnemonic('F');
		fileMenu.setText("File");
		fileMenu.setToolTipText("File-related items");
		fileMenu.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				fileMenuActionPerformed(evt);
			}
		});

		exitMenuItem.setIcon(new javax.swing.JLabel() {
			public javax.swing.Icon getIcon() {
				try {
					return new javax.swing.ImageIcon(
							new java.net.URL(
									"http://www.thestar.com/App_Themes/TheStar/images/icons/iconPrint.gif"));
				} catch (java.net.MalformedURLException e) {
				}
				return null;
			}
		}.getIcon());
		exitMenuItem.setMnemonic('x');
		exitMenuItem.setText("Exit");
		exitMenuItem.setToolTipText("Exit the application");
		exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				exitMenuItemActionPerformed(evt);
			}
		});

		fileMenu.add(exitMenuItem);

		mainMenuBar.add(fileMenu);

		editMenu.setMnemonic('E');
		editMenu.setText("Edit");
		mainMenuBar.add(editMenu);

		setJMenuBar(mainMenuBar);

		org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(
				getContentPane());
		getContentPane().setLayout(layout);
		layout
				.setHorizontalGroup(layout
						.createParallelGroup(
								org.jdesktop.layout.GroupLayout.LEADING)
						.add(jPanel1,
								org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
								org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
								Short.MAX_VALUE)
						.add(
								layout
										.createSequentialGroup()
										.addContainerGap()
										.add(
												leftSidePanel,
												org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
												org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
												org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
										.addPreferredGap(
												org.jdesktop.layout.LayoutStyle.RELATED)
										.add(
												rightSidePanel,
												org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
												org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
												org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
										.addContainerGap(
												org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
												Short.MAX_VALUE))
						.add(
								layout
										.createSequentialGroup()
										.addContainerGap()
										.add(
												cameraStatusBar1,
												org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
												728, Short.MAX_VALUE)
										.addContainerGap()));

		layout.linkSize(new java.awt.Component[] { leftSidePanel,
				rightSidePanel }, org.jdesktop.layout.GroupLayout.HORIZONTAL);

		layout
				.setVerticalGroup(layout
						.createParallelGroup(
								org.jdesktop.layout.GroupLayout.LEADING)
						.add(
								layout
										.createSequentialGroup()
										.add(
												jPanel1,
												org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
												org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
												org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
										.addPreferredGap(
												org.jdesktop.layout.LayoutStyle.RELATED)
										.add(
												layout
														.createParallelGroup(
																org.jdesktop.layout.GroupLayout.LEADING)
														.add(
																leftSidePanel,
																org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
																org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
																org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
														.add(
																rightSidePanel,
																org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
																org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
																org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
										.addPreferredGap(
												org.jdesktop.layout.LayoutStyle.RELATED)
										.add(
												cameraStatusBar1,
												org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
												org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
												org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
										.addContainerGap()));

		layout.linkSize(new java.awt.Component[] { leftSidePanel,
				rightSidePanel }, org.jdesktop.layout.GroupLayout.VERTICAL);

		pack();
	}// </editor-fold>//GEN-END:initComponents

	//GEN-FIRST:event_snapshotPhotoButtonActionPerformed
	private void snapshotPhotoButtonActionPerformed(
			java.awt.event.ActionEvent evt) {
		saveSnapshot();
	}//GEN-LAST:event_snapshotPhotoButtonActionPerformed

	//GEN-FIRST:event_goButtonActionPerformed
	private void goButtonActionPerformed(java.awt.event.ActionEvent evt) {
		takeSnapshot();
	}//GEN-LAST:event_goButtonActionPerformed

	//GEN-FIRST:event_previewPhotoButtonActionPerformed
	private void previewPhotoButtonActionPerformed(
			java.awt.event.ActionEvent evt) {
		savePreviewPhoto();
	}//GEN-LAST:event_previewPhotoButtonActionPerformed

	//GEN-FIRST:event_stopButtonActionPerformed
	private void stopButtonActionPerformed(java.awt.event.ActionEvent evt) {
		stopPreview();
	}//GEN-LAST:event_stopButtonActionPerformed

	//GEN-FIRST:event_previewButtonActionPerformed
	private void previewButtonActionPerformed(java.awt.event.ActionEvent evt) {
		//preview();
		System.out.println("Use preview buttons on pane, instead");
	}//GEN-LAST:event_previewButtonActionPerformed

	//GEN-FIRST:event_jButton1ActionPerformed
	private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
		// TODO add your handling code here:
	}//GEN-LAST:event_jButton1ActionPerformed

	//GEN-FIRST:event_portSelectButtonActionPerformed
	private void portSelectButtonActionPerformed(java.awt.event.ActionEvent evt) {
		selectComPort();
	}//GEN-LAST:event_portSelectButtonActionPerformed

	private void selectComPort() {
		System.out.println("Selecting com port");
		Map ports = PortAvailabilityUtil.getAvailableSerialPortMap();
		String[] portNames = {};
		portNames = (String[]) ports.keySet().toArray(portNames);
		PortPickerDialog pd = new PortPickerDialog(null, true, portNames,
				(commPort != null) ? commPort.getName() : null);
		pd.setVisible(true);
		if (pd.isOkClicked()) {
			String selected = (String) pd.getPortListBox().getSelectedValue();
			if (selected != null) {
				this.commPort = (CommPortIdentifier) ports.get(selected);
			}
			if (this.commPort != null) {
				setTitle(DEFAULT_TITLE + " " + commPort.getName());
			}
		}
		syncCamera();
		syncButton.setEnabled(this.commPort != null);

	}

	private void setCommPortByName(String commPortName) {
		Map ports = PortAvailabilityUtil.getAvailableSerialPortMap();
		this.commPort = (CommPortIdentifier) ports.get(commPortName);
		if (this.commPort == null) {
			selectComPort();
		}
	}

	//GEN-FIRST:event_exitMenuItemActionPerformed
	private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {
		exit();
	}//GEN-LAST:event_exitMenuItemActionPerformed

	//GEN-FIRST:event_resetButtonActionPerformed
	private void resetButtonActionPerformed(java.awt.event.ActionEvent evt) {
		resetCamera();
	}//GEN-LAST:event_resetButtonActionPerformed

	//GEN-FIRST:event_syncButtonActionPerformed
	private void syncButtonActionPerformed(java.awt.event.ActionEvent evt) {
		syncCamera();
	}//GEN-LAST:event_syncButtonActionPerformed

	/**
	 * @param args the command line arguments
	 */
	public static void main(String args[]) {
		java.awt.EventQueue.invokeLater(new Runnable() {
			public void run() {
				String comPort = "COM5";
				if (System.getProperty("os.name").indexOf("Windows") != -1) {
					System.out.println("COMPUTERNAME: "
							+ System.getenv("COMPUTERNAME"));
					if (System.getenv("COMPUTERNAME").equals("JGKVISTA")) {
						comPort = "COM1";
					}
				}
//				comPort=null;
				new CameraFrame(comPort).setVisible(true);
			}
		});
	}

	//GEN-BEGIN:variables
	// Variables declaration - do not modify
	private com.javapda.app.camera.gui.CameraStatusBar cameraStatusBar1;
	private javax.swing.JMenu editMenu;
	private javax.swing.JMenuItem exitMenuItem;
	private javax.swing.JMenu fileMenu;
	private javax.swing.JButton goButton;
	private javax.swing.JPanel jPanel1;
	private javax.swing.JPanel leftSidePanel;
	private javax.swing.JMenuBar mainMenuBar;
	private javax.swing.JButton playButton;
	private javax.swing.JButton portSelectButton;
	private javax.swing.JButton previewButton;
	private javax.swing.JButton previewPhotoButton;
	private javax.swing.JPanel previewPicturePane;
	private com.javapda.app.camera.gui.PreviewSettingsPanel previewSettingsPanel1;
	private javax.swing.JButton resetButton;
	private javax.swing.JPanel rightSidePanel;
	private javax.swing.JButton snapshotPhotoButton;
	private javax.swing.JPanel snapshotPicturePane;
	private javax.swing.ButtonGroup snapshotResolutionGroup;
	private com.javapda.app.camera.gui.SnapshotSettingsPanel snapshotSettingsPanel1;
	private javax.swing.JButton stopButton;
	private javax.swing.JButton syncButton;

	// End of variables declaration//GEN-END:variables

	private void fileMenuActionPerformed(ActionEvent evt) {
		System.out.println("File Menu Action");
	}

	private void resetCamera() {
		System.out.println("Resetting camera");
	}

	void syncCamera() {
		resetButton.setEnabled(false);
		playButton.setEnabled(false);
		stopButton.setEnabled(false);
		goButton.setEnabled(false);
		syncButton.setEnabled(false);
		System.out.println("Sync Camera on port " + commPort.getName());
		stopPreview();
		// perform sync
		if (serialPort == null) {
			setupSerialPort(commPort);
		}
		cam = new C328rCameraImpl(serialPort);
		C328rCameraConfiguration cfg = new C328rCameraConfiguration();
		cam.setConfiguration(cfg);
		//		cam.powerSwitch(true);
		resetButton.setEnabled(cam.isOn());
		//previewButton.setEnabled(cam.isOn());
		playButton.setEnabled(cam.isOn());
		goButton.setEnabled(cam.isOn());
		syncButton.setEnabled(true);
	}

	private void playButtonActionPerformed(ActionEvent evt) {
		System.out.println("Play Button Pressed");
		playPreview();
	}

	void playPreview() {
		// spawn the preview thread
		previewRunnable = new PreviewRunnable(this);
		Thread t = new Thread(previewRunnable,"Mr. Preview Threadatron");
		t.start();
		// 
		playButton.setEnabled(false);
		stopButton.setEnabled(true);

	}

	private void stopPreview() {
		System.out.println("Stop preview");
		if (previewRunnable != null) {
			previewRunnable.setRunning(false);
			previewRunnable = null;
			MiscUtil.pause(100);
		}
		if ( cam!=null && cam.isOn()) {
			playButton.setEnabled(true);
			stopButton.setEnabled(false);
		}
		
	}

	boolean preview() {
		previewPic = cam.getJpegPreview();
		if (previewPic != null) {
			setPreviewPhoto(previewPic);
			return true;
		} else {
			System.out.println("PREVIEW-OUCH");
			return false;
		}

	}

	private boolean setupSerialPort(CommPortIdentifier commPortIdentifier) {
		boolean portSetupSuccessful = false;
		try {
			CommPort commPort = commPortIdentifier.open(this.getClass()
					.getName(), 2000);
			if (serialPort!=null) {
				serialPort.close();
				serialPort=null;
			}
			serialPort = (SerialPort) commPort;
			serialPortReport();
			int baudrate = 19200;//115200; //57600;
			int dataBits = SerialPort.DATABITS_8;
			int stopBits = SerialPort.STOPBITS_1;
			int parity = SerialPort.PARITY_NONE;
			serialPort
					.setSerialPortParams(baudrate, dataBits, stopBits, parity);
			serialPort.setOutputBufferSize(512);
			serialPort.setInputBufferSize(512);
			System.out.println("__________________________________________");
			serialPortReport();
			System.out.println("__________________________________________");
			portSetupSuccessful = true;

		} catch (UnsupportedCommOperationException e) {
			e.printStackTrace();
		} catch (PortInUseException e) {
			e.printStackTrace();
		}
		return portSetupSuccessful;
	}

	private void serialPortReport() {
		StringBuilder sb = new StringBuilder();
		String SEP=",";
		sb.append("isCD=");
		sb.append(serialPort.isCD());
		sb.append(SEP);
		sb.append("isCTS=");
		sb.append(serialPort.isCTS());
		sb.append(SEP);
		sb.append("isDSR=");
		sb.append(serialPort.isDSR());
		sb.append(SEP);
		sb.append("isDTR=");
		sb.append(serialPort.isDTR());
		sb.append(SEP);
		sb.append("InputBufferSize=");
		sb.append(serialPort.getInputBufferSize());
		sb.append(SEP);
		sb.append("OutputBufferSize=");
		sb.append(serialPort.getOutputBufferSize());
		sb.append(SEP);
		sb.append("BaudRate=");
		sb.append(serialPort.getBaudRate());
		System.out.println(sb.toString());
	}

	private void exit() {
		System.out.println("Exit called");
		System.exit(1);
		System.out.println("Close serial port");
		if (serialPort != null) {
			serialPort.close();
			serialPort = null;
		}
		System.out.println("Bye bye");
		System.exit(1);
	}

	private void savePreviewPhoto() {
		System.out.println("Saving preview photo");
		if ( previewPic == null ) {
			System.out.println("No preview to save");
		} else {
			System.out.println("Saving preview");
			writeBytesToFile("preview",previewPic);
		}
	}

	private void takeSnapshot() {
		System.out.println("Take snapshot");
		snapshotPic = cam.getSnapshot();
		setSnaphotPhoto(snapshotPic);
	}
	
	private void saveSnapshot() {
		System.out.println("Save snapshot");
		if ( snapshotPic == null ) {
			System.out.println("No snapshot to save");
		} else {
			System.out.println("Saving snapshot");
			writeBytesToFile("snapshot",snapshotPic);
		}
	}

	public Component getPreviewButton() {
		return this.previewButton;
	}

	private void writeBytesToFile(final String tag, byte[] imageBytes) {
		final byte[] imgFileBytes = new byte[imageBytes.length];
		synchronized (imageBytes) {
			System.arraycopy(imageBytes, 0, imgFileBytes, 0, imageBytes.length);
		};
		new Thread(new Runnable() {
			public void run() {
				Date date = new Date();
				DateFormat df = new SimpleDateFormat("yyyyMMdd_HHmmss");
				String fileName = tag + df.format(date) + "_"+System.currentTimeMillis()+".jpg";
				File file = new File(".",fileName);
				try {
					FileUtil.writeBytesToFile(imgFileBytes, file);
					if ( file.exists() ) {
						System.out.println("File: "+file.getAbsolutePath() + ", length="+(file.length()/1000.)+" kb" );
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}).start();
	}
	
}